#include "../include/BaseLib.hpp"

int main()
{
	int sockfd, ret, on, count;
	char recvbuf[BUF_SIZE] = { 0 };
	char sendbuf[BUF_SIZE] = { 0 };
	sockaddr_in server_address;
	memset(&server_address, 0, sizeof(server_address));
	printf("Start Build Socket");
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	ERROR_FUNC(sockfd < 0,"socket");
	printf("create client socket success [socket = %d]!\n",sockfd);
	server_address.sin_family = AF_INET;
	server_address.sin_port = htons(SERVER_PORT);
	inet_pton(AF_INET, SERVER_ADDRESS, &server_address.sin_addr);
	ret = connect(sockfd, (sockaddr*)&server_address, sizeof(server_address));
	ERROR_FUNC(ret<0,"connect");
	printf("Success connection to Server\n");

	fd_set rset;
	FD_ZERO(&rset);
	int maxfd = -1;
	int fd_stdin = fileno(stdin);
	if (fd_stdin > sockfd) maxfd = fd_stdin;
	else maxfd = sockfd;

	while (1)
	{
		FD_SET(fd_stdin, &rset);
		FD_SET(sockfd, &rset);
		ret = select(maxfd + 1, &rset, NULL, NULL, NULL);
		ERROR_FUNC(ret < 0,"select");
		if (ret == 0) continue;
		if (FD_ISSET(sockfd, &rset))
		{
			ret = read(sockfd, recvbuf, BUF_SIZE);
			ERROR_FUNC(ret<0,"read");
			if (ret == 0){
				printf("Server close \n");
				break;
			}
			printf("read message form server = [%s]\n", recvbuf);
			memset(recvbuf, 0, BUF_SIZE);
		}
		if (FD_ISSET(fd_stdin, &rset))
		{
			if (fgets(sendbuf, BUF_SIZE, stdin) == NULL) break;
			char* find;
			find = strchr(sendbuf, '\n');
			if (find) *find = '\0';
			count = send(sockfd, sendbuf, strlen(sendbuf), 0);
			ERROR_FUNC(count < 0, "send");
			memset(sendbuf, 0, BUF_SIZE);
		}
	}
	return 0;
}